<template>
  <Svga v-if="param.loading" :width="50" :height="50"></Svga>
  <div v-else class="app-container">
    <div style="font-weight: 700;font-size: 16px; padding-bottom: 10px;">
      订单号：{{ rowData.orderNo }}
    </div>
    <Progress :userRole="'boxOwnner'" :orderStatus="param.newStep" :payStatus="rowData.payStatus" />
    <div class="order-info">
      <el-row v-if="param.newStep < 35" style="margin-bottom: 10px">
        <el-button v-if="param.newStep >= 10" icon="edit" @click="handleShowPacking">查看提箱单</el-button>
        <!-- 回调统一在财务管理中开发票 -->
        <el-button v-if="rowData.invoiceStatus == 10" icon="edit" @click="drawer5Tap">开发票</el-button> 
        <el-button v-if="param.newStep >= 10 && rowData.invoiceStatus == 15" icon="edit"
          @click="param.drawerInvoiceInfo = true">查看发票</el-button>
        <el-button-group v-if="param.newStep >= 20" style="margin-left:20px; ">
          <el-button v-if="param.newStep <= 30 && !rowData.returnBoxNo" icon="edit"
            @click="handleCreateOrder('huanXiang')">开还箱单据</el-button>
          <el-button v-if="rowData.returnBoxNo" icon="edit" @click="handleShowReturn">查看还箱单</el-button>
        </el-button-group>
        <!-- <el-button @click="handleCreateOrder('tiXiang')" type="primary" round>开提箱单</el-button> -->
      </el-row>

      <el-row :gutter="10">
        <el-col :span="18">
          <el-card>
            <el-row :gutter="10">
              <el-col :span="10">
                <div style="font-weight: bold ;font-size: 16px;margin:10px 0 10px 0;">
                  <span style="width:3px;height:20px;background-color: #2158F3;"> &nbsp</span> &nbsp;租赁信息
                </div>
                <div style="margin-top: 10px;position: relative;">
                  <Carousel v-bind="swiperData" style="position: absolute;top: 0px;"></Carousel>
                </div>
              </el-col>
              <el-col :span="11">
                <div style="font-size: 16px;text-align: left; box-sizing: border-box;padding: 20px 40px 10px 40px;position: relative;">
                  <el-row :gutter="10">
                    <el-col :span="11">
                      <span style="font-weight: bold;font-size: 18px;">{{ rowData.carryCityName }}</span>
                      <div style="margin-top: 10px;color: #aaa;">
                        提箱城市：{{ rowData.carryCityName }}/{{ rowData.carryCountryName }}
                      </div>
                    </el-col>
                    <el-col :span="2"><img style="text-align: center; width: 20px;" src="@/assets/icons/svg/right.svg">
                    </el-col>
                    <el-col :span="11" style="text-align: right;">
                      <span style="font-weight: bold;font-size: 18px;">{{ rowData.returnCityName }}</span>
                      <div style="margin-top: 10px;color: #aaa;">
                        还箱城市：{{ rowData.returnCityName }}/{{ rowData.returnCountryName }}
                      </div>
                    </el-col>
                  </el-row>
                  <!-- stamp -->
                  <div style="position: absolute;right: -70px;">
                    <stamp :rowData="rowData" :rentSource="5" />
                    <stampCancel :rowData="rowData" :pageType="'rentBox'" :canceledType="rowData.canceledType" :roleType="'boxEast'" style="margin-right: 0;" />
                  </div>
                  <!-- stampCancel -->
                  <el-row class="marginTop30" align="middle">  
                    <el-col :span="6">租赁单价</el-col>
                    <el-col :span="5">
                      <el-tooltip class="box-item" effect="dark" :content="currency + rowData.unitPrice" placement="top">
                        <span style="color: #eb2a2a;width: 100%;display: inline-block;" class="text-ellipsis">{{ currency }} {{rowData.unitPrice}}</span>
                      </el-tooltip>
                    </el-col>
                    <el-col :span="3" class="text-center" v-if="!disabledStus" style="position: relative;"><el-icon size="20" style="position: absolute;top:-9px;left: 10px;"><Edit @click="modifyUnitPrice"/></el-icon></el-col>
                    <el-col :span="5" v-if="!disabledStus">
                      <el-radio-group v-model="param.checkRadeo" @change="changeRadio">
                        <!-- <template> -->
                            <el-radio value="CNY" size="large" :disabled="disabledStus">￥</el-radio>
                            <el-radio value="USD" size="large" :disabled="disabledStus">$</el-radio>
                        <!-- </template> -->
                        <!-- <template v-else>
                            <el-radio value="CNY" size="large">￥</el-radio>
                            <el-radio value="USD" size="large">$</el-radio>
                        </template> -->
                      </el-radio-group>
                    </el-col>
                  </el-row>
                  <el-row class="marginTop30">
                    <el-col :span="6">箱使期</el-col>
                    <el-col :span="5" style="position: relative;">
                      <el-tooltip class="box-item" effect="dark" :content="rowData.boxUsagePeriod + '天'" placement="top">
                        <span style="width: 100%;display: inline-block;" class="text-ellipsis">{{rowData.boxUsagePeriod}}天</span> 
                      </el-tooltip> 
                      <el-icon size="20" v-if="!disabledStus"  style="float: left;position: absolute;top:2px;left: 106px;cursor: pointer;"><Edit @click="modifyBoxUsagePeriod"/></el-icon>
                    </el-col>
                  </el-row>
                  <el-row class="marginTop30">
                    <el-col :span="6">箱型</el-col>
                    <el-col :span="12">{{ boxTypeFilter(rowData.boxType) }}</el-col>
                  </el-row>
                  <el-row class="marginTop30">
                    <el-col :span="6">箱况</el-col>
                    <el-col :span="12">{{ boxConditionFilter(rowData.boxCondition) }}</el-col>
                  </el-row>
                  <el-row class="marginTop30">
                    <el-col :span="6">箱量</el-col>
                    <el-col :span="12">{{ rowData.boxQuantity }} &nbsp;个</el-col>
                  </el-row>
                  <el-row class="marginTop30">
                    <el-col :span="6">预计提箱日期</el-col>
                    <el-col :span="12"> {{ formatDate(rowData.planPickupDate, 2) }}</el-col>
                  </el-row>
                  <el-row class="marginTop30">
                    <el-col :span="6">创建日期</el-col>
                    <el-col :span="12"> {{ formatDate(rowData.createTime,2) }}</el-col>
                  </el-row>
                </div>
              </el-col>
            </el-row>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card style="height: 100%;position:relative" >
            <!-- <div style="font-weight: 700;font-size: 15px;margin:10px 0 10px 0;">
              <span style="width:3px;height:10px;background-color: #2158F3;font-size: 12px;"> &nbsp</span>&nbsp租赁费用
            </div> -->
            <el-row class="marginTop20">
              <el-col :span="12">应收箱量</el-col>
              <el-col :span="12" class="text-right" >{{ rowData.containerQuantity || 0 }}</el-col>
            </el-row>
            <el-row class="marginTop10">
              <el-col :span="12">出租箱金额</el-col>
              <el-col :span="12" class="text-right" style="color: #eb2a2a;">{{ currency }} {{ totalAmount }}</el-col>
            </el-row>
            <el-row class="marginTop10"> 
              <el-col :span="12">优惠券</el-col>
              <el-col :span="12" class="text-right">{{ rowData.couponAmount || '0.00' }}</el-col>
            </el-row>
            <el-row style="border-top: #999999 1px dashed;position:absolute;bottom:20px;width: 88%;" class="marginTop10">
                <el-col :span="24">
                  <el-row class="marginTop10">
                    <el-col :span="12">合计</el-col>
                    <el-col :span="12" class="text-right" style="color: #eb2a2a;">{{ currency }} {{ totalAmount }}</el-col>
                  </el-row>
                  <!-- <el-row class="marginTop10">
                    <el-col :span="12" style="color: #aaa;">折合</el-col>
                    <el-col :span="12" style="color: #aaa;" class="text-right">{{ currency }} {{ totalAmount }}</el-col>
                  </el-row>
                  <el-row class="marginTop10">
                    <el-col :span="12" style="color: #aaa;">本单执行汇率</el-col>
                    <el-col :span="12" style="color: #aaa;" class="text-right">--</el-col>
                  </el-row> -->
                  <!-- <el-row class="marginTop10">
                    <el-col :span="12">应收出租箱款</el-col>
                    <el-col :span="12" class="text-right" style="color: #eb2a2a;">{{ currency }} {{ totalAmount }}</el-col>
                  </el-row> -->
                </el-col>
            </el-row>
          </el-card>
        </el-col>
      </el-row>
      <el-card class="pag-container">
        <div style="font-weight: 700;font-size: 15px;margin-top: 20px;">
          <span style="width:3px;height:20px;background-color: #2158F3;padding: 0 2px;margin-right: 5px;"></span>客户信息
        </div>
        <el-row class="marginTop30">
          <el-col :span="6">
            <el-row>
              <el-col :span="24">企业名称</el-col>
              <el-col :span="24" class="marginTop10">{{rowData.agentName}}</el-col>
            </el-row>
          </el-col>
          <el-col :span="4">
            <el-row>
              <el-col :span="24">联系人</el-col>
              <el-col :span="24" class="marginTop10">{{rowData.contacts}}</el-col>
            </el-row>
          </el-col>
          <el-col :span="4">
            <el-row>
              <el-col :span="24">联系电话</el-col>
              <el-col :span="24" class="marginTop10">
              <span v-if="rowData.agentUserAreaCode" style="margin-right: 10px;"> + {{ rowData.agentUserAreaCode }}</span>
                
                {{rowData.tel}}</el-col>
            </el-row>
          </el-col>
          <el-col :span="4">
            <el-row>
              <el-col :span="24">支付方式</el-col>
              <el-col :span="24" class="marginTop10">
                <el-select v-model="rowData.paymentMethod" disabled style="width:60%;min-width: 200px;" placeholder="选择">
                  <el-option v-for="item in param.paymentMethodList" :key="item.value" :label="item.label"
                    :value="item.value" />
                </el-select>
              </el-col>
            </el-row>
          </el-col>
          <el-col :offset="2" :span="4">
            <el-row>
              <el-col :span="24">结算账期</el-col>
              <el-col :span="24" class="marginTop10">
                <el-space> 
                  <el-input-number v-model="rowData.period" :disabled="disabledStus" :precision="0" :min="0" :max="365" @change="changePeriod">
                    <template #suffix>
                      <span>天</span>
                    </template>
                  </el-input-number>
                </el-space>
              </el-col>
            </el-row>
          </el-col>
          <el-col  :span="6" class="marginTop20">
            <el-row>
              <el-col :span="24">联系客户</el-col>
              <el-col :span="24" class="marginTop10">
                <el-icon>
                  <Comment />
                </el-icon>
              </el-col>
            </el-row>
          </el-col>
          <el-col :span="4" class="marginTop20">
            <el-row>
              <el-col :span="24">留言</el-col>
              <el-col :span="24" class="marginTop10">{{rowData.leaveMsg || '无'}}</el-col>
            </el-row>
          </el-col>
        </el-row>
      </el-card>
      <!-- 租箱人信息 -->
      <el-card class="pag-container">
        <span style="font-weight: 700;font-size: 15px;">
          <span style="width:3px;height:20px;background-color: #2158F3;padding: 0 2px;margin-right: 5px;"></span>出租人信息
        </span>

        <el-row  class="marginTop30">
          <el-col :span="4">
            <el-row>
              <el-col :span="24">出租人</el-col>
              <el-col :span="24" class="marginTop20">{{ user.nickname }}</el-col>
            </el-row>
          </el-col>
          <el-col :span="10">
            <el-row>
              <el-col :span="24"><redStar />操作员</el-col>
              <el-col :span="24" class="marginTop20">
                <el-select v-model="param.userSimple" @change="userSimpleChange" :disabled="![10].includes(rowData.currentNodeType) || rowData.frontNodeReviewStatus!=5" style="width: 150px;">
                  <el-option v-for="item in param.userSimpleList" :key="item.userId" :label="item.nickname"
                    :value="item.userId">
                  </el-option>
                </el-select>
              </el-col>
            </el-row>
          </el-col>
        </el-row>
      </el-card>

      <!-- 按钮/反馈信息展示 -->
      <el-card class="pag-container">
        <div v-if="rowData.rejectReason && rowData.currentNodeType == 10"
          style="text-align: center;margin-bottom: 20px;">
          <span>
            <span v-if="rowData.frontNodeType == 15">拒绝原因：</span>
            <span v-if="rowData.frontNodeType == 25">驳回原因：</span>
          </span>
          <span>{{ rowData.rejectReason }} </span>
        </div>
        <div v-if="rowData.status == 40 && rowData.canceledType == 10" style="text-align: center;margin-bottom: 20px;">
          <span> 取消原因： </span>
          <span>{{ rowData.remark }} </span>
        </div>
        <div v-if="rowData.currentNodeType == 20" style="width: 80%;margin: 0 auto;">
          <div style="font-weight: 700;font-size: 15px;">
            <span style="width:3px;height:20px;background-color: #2158F3;"> &nbsp</span>审核信息
          </div>
          <h4>
            <redStar />驳回原因
          </h4>
          <el-input type="textarea" :rows="4" v-model="rowData.reviewRemark" placeholder="请输入驳回原因" />
        </div>
        <div style="width:100%;text-align: center;margin-top: 10px;">
          <!-- <div style="margin-bottom: 20px;" v-if="rowData.currentNodeType == 10 && param.newStep < 5">
            <el-checkbox v-model="checked1" label="" size="large" />
             我已阅读<router-link to="/boxRules">
              《集装箱租赁业务规则》、
              《用户服务协议和管理规则》
            </router-link>并同意全部条款
          </div> -->
          <template v-if="rowData.status == 40 && rowData.canceledType == 10">
            <el-button @click="handleShowWarning('rejectCancel')" type="danger">拒绝</el-button>
            <el-button v-if="rowData.currentNodeType == 10" @click="handleMakeSure" type="primary">同意
            </el-button>
          </template>
          <template v-if="rowData.status < 35">
            <!-- <el-button v-if="(param.newStep == 5 || param.newStep == 30) && !rowData.packingNo"
                @click="handleCreateOrder('tiXiang')" type="primary" round>开提箱单</el-button> -->
            <el-button v-if="(param.newStep == 5 || param.newStep == 30) && !rowData.packingNo" @click="handlePacking"
              type="primary">开提箱单</el-button>
            <el-button v-if="param.newStep <= 15 && rowData.status != 3" @click="handleShowWarning('cancelOrder')">
              取消订单</el-button>
            <el-button v-if="rowData.currentNodeType == 10 && param.newStep < 5" @click="handleMakeSure" type="primary">确认</el-button>
          </template>
          <template v-if="rowData.currentNodeType == 20">
            <el-button @click="handleReject('rejectOrder')" type="danger">驳回</el-button>
            <el-button @click="handleMakeSure" type="primary">通过</el-button>
          </template>
          <el-button v-if="rowData.currentNodeType == 30 && rowData.status == 3" @click="showContract" type="primary">签署</el-button>
        </div>
      </el-card>
    </div>

    <!-- E签宝 -->
    <el-dialog v-model="param.dialogEVisibleWarning" @close="handleCloseEQianBao" title="签署" style="width: auto;">
      <iframe v-if="param.dialogEVisibleWarning" :src="param.longContractUrl" width="100%" height="800px"
        frameborder="0"></iframe>
    </el-dialog>

    <!-- 开提箱单 -->
    <el-drawer v-model="param.drawerPacking" :show-close="false" size="40%" :with-header="false"> 
      <el-row>
        <el-col :span="6">
          <span class="_before">开提箱单</span>
        </el-col>
      </el-row>
      <el-row align="middle">
        <el-col :span="4"><redStar />提箱单类型</el-col>
        <el-col :span="8" >
          <el-radio-group v-model="param.packingType">
            <el-radio value = "5" size="large">自有箱</el-radio>
            <el-radio value = "15" size="large">外调箱</el-radio>
          </el-radio-group>
        </el-col>
      </el-row>
      <OwnBox v-if="param.packingType == '5' " :packingInfo="param.packingInfo"  :orderType="5" @closeDialog="closeDialog"></OwnBox> 
      <!--自有箱-->
      <ExternalBox v-if="param.packingType == '15'" :packingInfo="param.packingInfo" :orderType="5" @closeDialog="closeDialog"></ExternalBox>
    </el-drawer>

    <!-- drawer -->
    <!-- 开提箱单/开还箱单 -->
    <el-drawer v-model="param.drawer1" :with-header="false" size="40%">
      <span style="font-weight: 700;font-size: 15px;">
        <span style="width:3px;height:20px;background-color: #2158F3;"> &nbsp</span>
        <span v-if="param.opt == 'huanXiang'">开还箱单据</span>
        <span v-if="param.opt == 'tiXiang'">开提箱单</span>
      </span>
      <div style="margin-top: 40px;">
        <span>租箱订单</span>
      </div>
      <el-table :data="param.rentOrderTable" style="width: 100%;">
        <el-table-column prop="orderNo" label="订单号" width="200"> </el-table-column>
        <el-table-column label="预计提箱日期" width="120">
          <template #default="scope">
            {{ formatDate(scope.row.planPickupDate, 2) }}
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="下单日期" width="180">
          <template #default="scope">
            {{ formatDate(scope.row.createTime, 2) }}
          </template>
        </el-table-column>
        <template v-if="param.opt == 'huanXiang'">
          <el-table-column prop="returnedNum" label="已还箱量"> </el-table-column>
          <el-table-column prop="unReturnNum" label="未还箱量"> </el-table-column>
        </template>
        <template v-else>
          <el-table-column prop="packingedNum" label="已开箱量"> </el-table-column>
          <el-table-column prop="unPackingNum" label="未开箱量"> </el-table-column>
        </template>
      </el-table>
      <div v-if="param.opt == 'huanXiang'" style="margin-top: 40px;">
        箱型量：{{ boxTypeFilter(rowData.boxType) }} * {{ rowData.packedQuantity }}
      </div>
      <div v-else>
        <div style="margin-top: 40px;">箱型/箱量/箱况</div>
        <el-table :data="param.rentBoxTable" style="width: 100%">
          <el-table-column prop="boxType" label="箱型" width="180"> </el-table-column>
          <el-table-column prop="boxQuantity" label="箱量" width="180"> </el-table-column>
          <el-table-column prop="boxCondition" label="箱况"> </el-table-column>
        </el-table>
      </div>
      <el-form :model="param" ref="packingFormRef" :rules="packingRules" style="margin-top: 40px;">
        <!-- 还箱单 -->
        <div v-if="param.opt == 'huanXiang'">
          <el-form-item>
            <div>
              <redStar />单据类型
            </div>
            <el-select v-model="param.returnBoxType" style="width: 100%;" placeholder="请选择">
              <el-option v-for="item in param.returnBoxTypeList" :key="item.value" :label="item.label"
                :value="item.value" />
            </el-select>
          </el-form-item>
          <template v-if="param.returnBoxType == 5">
            <el-form-item prop="instructionNum">
              <div>
                <redStar />还箱指令号
              </div>
              <el-input v-model="param.instructionNum" style="width: 100%;" placeholder="请输入"></el-input>
            </el-form-item>
            <el-form-item prop="returnValidityPeriod">
              <div>
                <redStar />还箱单有效期范围
              </div>
              <el-date-picker v-model="param.returnValidityPeriod" type="daterange" range-separator="~"
                start-placeholder="开始日期" end-placeholder="结束日期" style="width: 100%;" />
            </el-form-item>
          </template>
        </div>
        <div v-if="param.returnBoxType == 15">
          <el-form-item prop="instructionNum">
            <div>
              <redStar />还箱指令号
            </div>
            <el-input v-model="param.instructionNum" style="width: 100%;" placeholder="请输入"></el-input>
          </el-form-item>
          <el-form-item prop="returnValidityPeriod">
            <div>
              <redStar />还箱令有效期范围
            </div>
            <el-date-picker v-model="param.returnValidityPeriod" type="daterange" range-separator="~"
              start-placeholder="开始日期" end-placeholder="结束日期" style="width: 100%;" />
          </el-form-item>
        </div>
        <!-- 提箱单 -->
        <div v-if="param.opt == 'tiXiang'">
          <el-form-item prop="instruction">
            <div>
              <redStar />放箱指令号
            </div>
            <el-input v-model="param.instruction" style="width: 100%;" placeholder="请输入"></el-input>
          </el-form-item>
          <el-form-item prop="packingValidityPeriod">
            <div>
              <redStar />提箱单有效期范围
            </div>
            <el-date-picker v-model="param.packingValidityPeriod" type="daterange" range-separator="~"
              start-placeholder="开始日期" end-placeholder="结束日期" style="width: 100%;" />
          </el-form-item>
        </div>
        <el-form-item prop="yardName">
          <div>
            <redStar />堆场名称
          </div>
          <yardSelect v-model="param.yardName" :selectName="'yardName'" :needInfo="true" @yardId="yardInfoData"
            style="width:100%" :placeholder="'请输入堆场名称'">
          </yardSelect>
        </el-form-item>
        <el-form-item>
          <div>
            <redStar />堆场地址
          </div>
          <el-input v-model="yardInfo.yardAddress" disabled style="width: 100%;" placeholder="请输入"></el-input>
        </el-form-item>
        <el-form-item prop="contacts">
          <div>
            <redStar />联系人
          </div>
          <!-- <el-input v-model="yardInfo.contacts" disabled style="width: 100%;" placeholder="请输入"></el-input> -->
          <el-select v-model="yardInfo.contacts" @change="handleYardContactsChange">
            <el-option v-for="item in yardInfo.yardContacts" :key="item.yardContactSerialNo" :label="item.contacts"
              :value="item">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <div>
            <redStar />联系电话
          </div>
          <el-input v-model="yardInfo.tel" disabled style="width: 100%;" placeholder="请输入">
            <template #prepend v-if="yardInfo?.areaCode">+{{yardInfo.areaCode}}</template>
          </el-input>
        </el-form-item>
        <el-form-item>
          <div>
            <redStar />堆场作业时间
          </div>
          <el-input v-model="yardInfo.workTime" disabled style="width:100%" placeholder="请输入" />
        </el-form-item>
        <el-form-item v-if="param.opt == 'huanXiang' && param.returnBoxType == 10" prop="boxOwnerContent">
          <div>
            <redStar />箱属内容
          </div>
          <el-input v-model="param.boxOwnerContent" placeholder="请输入"></el-input>
        </el-form-item>
      </el-form>
      <div style="padding: 40px 0 10px 0;">
        <redStar v-if="param.opt == 'huanXiang'" />
        <el-button @click="choiceBox" :disabled="!yardInfo.id" icon="edit">选择箱号</el-button>
      </div>
      <el-table :data="selectBoxList">
        <el-table-column prop="containerNo" label="箱号" />
        <!-- <el-table-column prop="boxType" label="箱型" /> -->
      </el-table>
      <div style="margin-top: 40px;">
        <span v-if="param.opt == 'huanXiang'">
          <!-- <span>还箱单附件</span> -->
          <redStar />
          <span v-if="param.returnBoxType == 10">箱属附件</span>
          <span v-if="param.returnBoxType == 15"> 还箱令附件 </span>
        </span>
        <span v-else>提箱单附件 </span>
      </div>
      <img-upload ref="packingRef" />
      <div v-if="param.newStep < 20">
        <div style="margin-top: 40px;">备注 </div>
        <el-input v-model="param.remark" type="textarea" placeholder="请输入内容" />
      </div>
      <div style="margin-top: 40px;height: 50px;">
        <el-button v-if="param.opt == 'huanXiang'" @click="handleSubmit('drawer1', 25)" type="primary"
          style="float: right;width: 100px;"> 提交
        </el-button>
        <el-button v-else @click="handleSubmit('drawer1', 10)" type="primary" style="float: right;width: 100px;"> 提交
        </el-button>
      </div>
    </el-drawer>

    <!-- <el-drawer v-model="param.drawerAddPanel" :with-header="false" size="40%">
      <addPackingPanel :rowData="rowData" /> 
    </el-drawer> -->

    <!-- 集装箱选择 -->
    <el-drawer v-model="param.drawer2" :with-header="false">
      <span style="font-weight: 700;font-size: 15px;">
        <span style="width:3px;height:20px;background-color: #2158F3;"> &nbsp</span>集装箱选择
      </span>
      <el-input v-model="param.containerNo" @input="getBoxInYard" type="text" placeholder="请输入箱号"
        style="float: right;margin-top: 40px;" />
      <div style="height:40px"></div>
      <el-table :data="param.selectBoxTable" @selection-change="handleSelectionBoxChange" style="margin-top: 90px;">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="containerNo" label="箱号" width="200"> </el-table-column>
        <el-table-column prop="boxType" label="箱型" width="180"> </el-table-column>
        <el-table-column prop="boxCondition" label="箱况"> </el-table-column>
        <!-- <el-table-column prop="inDays" label="堆存天数" width="180"> </el-table-column> -->
      </el-table>
      <div style="margin-top: 40px;height: 50px;">
        <el-button @click="handleChoiceBox" type="primary" style="float: right;width: 100px;"> 确定 </el-button>
      </div>
    </el-drawer>
    <!-- 租箱订单选择 -->
    <el-drawer v-model="param.drawer" size="50%" :with-header="false">
      <span style="font-weight: 700;font-size: 15px;">
        <span style="width:3px;height:20px;background-color: #2158F3;"> &nbsp</span>租箱订单选择
      </span>
      <el-input v-model="param.orderNo" @input="getTableData" type="text" placeholder="请输入租箱订单号"
        style="float: right;margin-top: 40px;" />
      <el-table :data="param.selectTable" @selection-change="handleSelectionChange" style="margin-top: 90px;">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="orderNo" label="订单号" width="200"> </el-table-column>
        <el-table-column prop="boxType" label="箱型" width="100"> </el-table-column>
        <el-table-column prop="boxQuantity" label="箱量"> </el-table-column>
        <el-table-column prop="boxCondition" label="箱况" width="100"> </el-table-column>
        <el-table-column prop="planPickupDate" label="预计提箱日期" width="180"> </el-table-column>
        <el-table-column prop="createTime" label="下单日期"> </el-table-column>
      </el-table>
      <div style="margin-top: 40px;height: 50px;">
        <el-button @click="handleChoice" type="primary" style="float: right;width: 100px;"> 确定 </el-button>
      </div>
    </el-drawer>
    <!-- 还箱/提箱单 信息 -->
    <tixiangdanInfo ref="tixiangdanInfoRef" @tixiangdanInfoClick="txClick"  @tixiangdanInfoListClick="txListClick"></tixiangdanInfo>
    <huanxiangdanInfo ref="huanxiangdanInfoRef" @huanxiangdanInfoClick="hxClick"  @huanxiangdanInfoListClick="hxListClick"></huanxiangdanInfo>

    <!-- 还箱记录/提箱记录 -->
    <el-drawer v-model="param.drawer4" :with-header="false">
      <packingRecord :rowData="packingInfo" :oprName="param.oprName" :roleName="'boxEast'"></packingRecord>
    </el-drawer>
    <!-- 开发票 -->
    <el-drawer v-model="param.drawer5" :with-header="false">
      <span style="font-weight: 700;font-size: 15px;">
        <span style="width:3px;height:20px;background-color: #2158F3;"> &nbsp</span>开发票
      </span>
      <div>
        <el-form label-width="200" style="margin: 50px 0 50px 100px;">
          <el-form-item label="申请发票类型：">{{ { 5: '对公转账', 10: '在线支付' }[invoiceInfoDatai.invoiceType] }}</el-form-item>
          <el-form-item label="企业名称：">{{ rowData.invoiceTitle }}</el-form-item>
          <el-form-item label="统一社会信用代码：">{{ invoiceInfoDatai.creditCode }}</el-form-item>
          <el-form-item label="发票：">
            <img-upload ref="invoiceRef" :needOcr="true" :drag="false" @ocrInvoiceNo="ocrInvoiceNo" />
          </el-form-item>
          <el-form-item label="发票号：" style="width: 400px;">
            <el-input v-model="param.invoiceNo" placeholder="请输入发票号" />
          </el-form-item>
        </el-form>
        <b>明细</b>
        <el-table :data="rentFeeDetail">
          <el-table-column prop="orderNo" label="订单号"> </el-table-column>
          <el-table-column prop="carryCity" label="提箱城市"> </el-table-column>
          <el-table-column prop="ReturnCity" label="还箱城市"> </el-table-column>
          <el-table-column prop="createTime" label="下单日期"> </el-table-column>
          <el-table-column prop="boxQuantity" label="箱量" width="120"> </el-table-column>
          <el-table-column prop="amount" label="订单金额(￥)" width="120"> </el-table-column>
          <el-table-column prop="containerQuantity" label="应收箱量" width="120"> </el-table-column>
          <el-table-column prop="actualPayAmount" label="应收租箱款(￥)" width="120"> </el-table-column>
        </el-table>
        <b>合计</b>
        <el-table :data="rentFeeTotal">
          <el-table-column prop="needPayContainerNum" label="应收箱量"> </el-table-column>
          <el-table-column prop="dealAmount" label="应收租箱费总计"> </el-table-column>
          <el-table-column prop="deductAmount" label="实收租箱费总计" width="120"> </el-table-column>
        </el-table>
        <el-form label-width="200" style="margin: 30px 0 50px 100px;">
          <el-form-item label="结算币种：">
            <el-radio-group v-model="param.payCurrency">
              <el-radio value="USD" size="large">$</el-radio>
              <el-radio value="CNY" size="large">￥</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="本次执行汇率：">
            1美元 &nbsp;= &nbsp;
            <el-input-number v-model="param.rate" size="small" :controls="false" :min="1" :max="99.99" :precision="2"
              placeholder=" < 100" @blur="param.rate = param.rate ? param.rate : 1" style="width:100px" />
            &nbsp;元
          </el-form-item>
        </el-form>
      </div>
      <div style="margin-top: 50px;height: 50px;">
        <el-button @click="handleSubmit('drawer5', 20)" type="primary" style="float: left;width: 100px;"> 提交
        </el-button>
      </div>
    </el-drawer>
    <!-- 发票信息 -->
    <el-drawer v-model="param.drawerInvoiceInfo" :with-header="false">
      <invoiceInfo :rowData="rowData" :param="param"></invoiceInfo>
    </el-drawer>
    <!-- 重新上传 -->
    <el-drawer v-model="param.drawerReuploadInvoice" :with-header="false">
      <span style="font-weight: 700;font-size: 15px;">
        <span style="width:3px;height:20px;background-color: #2158F3;"> &nbsp</span>重新上传
      </span>
      <div>
        <div style=" margin-top: 20px;">
          <div>
            <redStar />上传发票
          </div>
          <img-upload ref="invoiceRef" :needOcr="true" @ocrInvoiceNo="ocrInvoiceNo" />
        </div>
        <div style="margin-top: 20px;">
          <div style="width: 100%;">
            <redStar />发票号
          </div>
          <el-input v-model="param.invoiceNo" placeholder="请输入发票号" style="width: 300px;" />
        </div>
      </div>
      <div style="margin-top: 50px;height: 50px;">
        <el-button @click="handleReuploadInvoice" type="primary" style="float: left;width: 100px;"> 提交
        </el-button>
      </div>
    </el-drawer>
    <!-- 确定取消订单吗？ -->
    <el-dialog v-model="param.dialogVisibleWarning" title="提示" style="width: 400px;">
      <el-form>
        <el-form-item v-if="param.warningName == 'cancelOrder'">
          <h3>确定取消订单吗？</h3>
        </el-form-item>
        <el-form-item prop="remark">
          <div v-if="param.warningName == 'cancelOrder'" style="width: 100%;">备注：</div>
          <div v-else style="width: 100%;">拒绝原因：</div>
          <el-input v-model="warningForm.remark" type="textarea" rows="3" max="200" show-word-limit placeholder="请输入原因"
            style="width: 300px;" />
        </el-form-item>
        <el-form-item>
          <el-button @click="handleCancel" type="primary" style="float: right;width: 100px;"> 确定
          </el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 修改箱使期/租赁单价 -->
    <el-dialog v-model="param.dialogBoxUsagePeriod" :title="param.modifyType == 'unitPrice'? '修改租赁单价': '修改箱使期'" align-center style="width: 400px;" >
        <el-row justify="center" align="middle" style="margin: 30px 0;"> 
          <el-col :span="5" class="text-right">
            <template v-if="param.modifyType == 'unitPrice'">租赁单价:&nbsp;&nbsp;&nbsp;</template>
            <template v-if="param.modifyType == 'boxUsagePeriod'">箱使期:&nbsp;&nbsp;&nbsp;</template>
          </el-col>
          <el-col :span="10"> 
            <template v-if="param.modifyType == 'unitPrice'"> <el-input v-model="param.unitPriceNumber" @input="handleInput" clearable autocomplete="off" /></template>
            <template v-if="param.modifyType == 'boxUsagePeriod'"> <el-input v-model="param.boxUsageNumber" @input="handleInput" clearable autocomplete="off" /></template>
          </el-col>
          <el-col :span="5">
            <template v-if="param.modifyType == 'unitPrice'">&nbsp;&nbsp;&nbsp;元</template>
            <template v-if="param.modifyType == 'boxUsagePeriod'">&nbsp;&nbsp;&nbsp;天</template>
            </el-col>
        </el-row>
        <template #footer>
            <div class="dialog-footer">
              <el-button @click="param.dialogBoxUsagePeriod = false">关闭</el-button>
              <el-button type="primary" @click="confirmNumber"> 确定</el-button>
            </div>
          </template>
    </el-dialog>

    
    <!-- 查看提箱单列表 -->
    <el-dialog v-model="param.pkdialogTable" title="提箱单列表">
      <el-table :data="param.packingList" header-align="center" >
        <el-table-column property="packingNo" label="提箱单号" align="center">
          <template #default="scope">
            <el-button link type="primary" size="default" @click.prevent="showPacking(scope.row)" >{{scope.row.packingNo}}</el-button>
          </template>
        </el-table-column>
        <el-table-column property="yardName" label="堆场名称" width="120" align="center"/>
        <el-table-column property="boxCondition" label="箱况" width="60" align="center"><!--箱况:boxCondition 5-全新   10-次新  15-适货 20-混提-->
          <template #default="scope">
            <template v-if="scope.row.boxCondition == 5">全新</template>
            <template v-if="scope.row.boxCondition == 10">次新</template>
            <template v-if="scope.row.boxCondition == 15">适货</template>
            <template v-if="scope.row.boxCondition == 20">混提</template>
            <template v-else>--</template>
          </template>
        </el-table-column>
        <el-table-column property="residuePackingDays" label="剩余提箱天数" width="110" align="center">
          <template #default="scope">
            {{scope.row.residuePackingDays}}天
          </template>
        </el-table-column>
        <el-table-column property="packingValidityPeriodStart" label="提箱单有效期范围" align="center">
          <template #default="scope">
            {{ scope.row.packingValidityPeriodStart?.substring(0,10) }}~{{scope.row.packingValidityPeriodEnd?.substring(0,10)}}
          </template>
        </el-table-column>
        <el-table-column property="agentName" label="客户" show-overflow-tooltip align="center"/>
        <el-table-column property="packingStatus" label="状态" width="80" align="center">  <!--提箱单状态:  5-已发放 10-已下载 15-提箱中 20-已完成 25-作废 30-已过期-->
          <template #default="scope">
            <template v-if="scope.row.packingStatus == 5">已发放</template>
            <template v-if="scope.row.packingStatus == 10">已下载</template>
            <template v-if="scope.row.packingStatus == 15">提箱中</template>
            <template v-if="scope.row.packingStatus == 20">已完成</template>
            <template v-if="scope.row.packingStatus == 25">作废</template>
            <template v-if="scope.row.packingStatus == 30">已过期</template>
            <template>--</template>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>
<script setup lang="ts">
import { formatDate} from '@/utils'
import OwnBox from '@/views/components/packingList/ownBox.vue';
import ExternalBox from '@/views/components/packingList/externalBox.vue';
import tixiangdanInfo from '@/views/components/order/tixiangdanInfo.vue';
import huanxiangdanInfo from '@/views/components/order/huanxiangdanInfo.vue';

import  Carousel from '@/components/carousel'
import addPackingPanel from '@/views/components/rent/addPackingPanel.vue'
import invoiceInfo from '@/views/components/order/invoiceInfo.vue'
import Svga from '@/views/components/Svga'
import { numAdd, numSub, numMulti } from '@/utils/compute'
import redStar from '@/views/components/redStar.vue';
import packingRecord from '@/views/components/tiXiangManage/packingRecord.vue'
import Progress from '@/components/progress/index.vue'
import { computed, getCurrentInstance, onActivated, reactive, ref,provide,watch } from 'vue';
import imgUpload from '@/components/upload/index.vue'
import orderInfo from '@/store/modules/order'
import { getTable, getOrderInfo, toIssueInvoice } from '@/api/orderManage'
import { getTable as getBoxTable } from '@/api/boxManage/index'
import { addPacking, getPackingData,rentBoxList } from '@/api/orderManage/packing'
import yardSelect from '@/components/citySelect/yardSelect.vue';
import { invoiceOcr, rentUploadingInvoice } from '@/api/invoice'
import { getTable as getReturnBoxTable, getBoxEastTable, getReturnData, addReturn, cancelReturn, downloadReturn } from '@/api/orderManage/returnBox'
import yardInfoCard from '@/views/components/boxYard/yardInfo.vue'
import { useRouter } from 'vue-router';
import { ElMessage, ElMessageBox, ElLoading, spaceItemProps } from 'element-plus';
import { cancelOrder } from '@/api/orderManage/index'
import validateChengZhi from '@/utils/validateChengZhi'
import { processApproved, processRejected } from '@/api/orderCheck/index'
import stamp from '@/views/components/stamp';
import { updateBoxPrice, updateBoxUsagePeriod, updateBoxRate } from '@/api/orderManage/index'
import { getContractList, getEqbContractOrderInfo } from '@/api/contract/eQianBao'
import stampCancel from '@/views/components/stamp/stampCancel';
import { getInvoicesInfo } from '@/api/invoice/index'
const checked1=ref(false)
const param = reactive({
  num: 1,
  activeNames: '',
  drawer: false,
  drawer1: false,
  drawer2: false,
  drawer3: false,
  drawer4: false,
  newStep: 5,
  dialogVisible: false,
  loading: false,
  //table 
  drawer2Data: [
    { key1: 'fwru0215650', key2: '40HQ', key3: '次新', key4: '32', }
  ],
  drawer3Data: [
    { key1: 'fwru0215650', key2: '40HQ', key3: '次新', key4: '32', key5: '2024/04/25', key6: '2024/04/25 13:39' }
  ],

  //开提箱单列表
  rentOrderTable: [{ orderNo: '', planPickupDate: '', createTime: '' }],
  rentBoxTable: [{ boxType: '', boxQuantity: '', boxCondition: '' }],
  selectTable: [{ orderNo: '', planPickupDate: '', createTime: '', boxType: '', boxQuantity: '', boxCondition: '' }],
  selectBoxTable: [{ containerNo: '', boxType: '', inDays: '', boxCondition: '' }],
  containerNoArry: [],

  //订单分配  
  paymentMethodList: [{ value: 5, label: '对公转账' }, { value: 10, label: '在线支付' }],
  operateUserList: [{ "operateUserId": 3, "operateUserName": "张三" }, { "operateUserId": 5, "operateUserName": "王五" }],
  businessUserList: [{ "businessUserId": 4, "businessUserName": "李四" }, { "businessUserId": 6, "businessUserName": "赵六" }],
  allocation: [{ 'operateUsers': [3, 5], "businessUser": 4, "businessNo": "NO1234567890" }],

  //
  returnBoxTypeList: [
    // { value: 5, label: '还箱单' },
    { value: 10, label: '箱属' },
    { value: 15, label: '还箱令' }
  ],
  dialogBoxUsagePeriod:false,
  boxUsageNumber:"",
  unitPriceNumber:"",
  checkRadeo: "",
  modifyType:"", //修改弹窗类型 boxUsagePeriod：修改箱使期  unitPrice：修改租赁单价
  pkdialogTable:false,//提箱单列表弹窗
  packingList:[], // 提箱单列表数据
  packingType:"5",
  packingInfo:[],// 需开提箱单信息
  payCurrency: 'USD',
  rate: 1,
})
const swiperData = reactive({
  list: [],
  config: {
    width:"100%",
    height:"450px"
  }
})
const currency = computed(() => {
  return rowData.value.currency == 'CNY' ? '￥' : '$'
})

//校验规则
const validatePlanPackingDate = (rule: any, value: any, callback: any) => {
  if (value[0] < new Date(new Date().setHours(0, 0, 0, 0))) {
    return callback(new Error('开始日期必须 大于等于 当前时间'))
  }
  return callback()
}
const packingRules = {
  instructionNum: [{ required: true, trigger: "blur", message: "不能为空" }],
  returnValidityPeriod: [
    { required: true, trigger: "blur", message: "不能为空" },
    { required: true, validator: validatePlanPackingDate, trigger: "blur" }
  ],
  instruction: [{ required: true, trigger: "blur", message: "不能为空" }, { pattern: /^[0-9a-zA-Z]{1,20}$/, trigger: "blur", message: "1-20位数字/字母" }],
  packingValidityPeriod: [
    { required: true, trigger: "blur", message: "不能为空" },
    { required: true, validator: validatePlanPackingDate, trigger: "blur" }
  ],
  yardName: [{ required: true, trigger: "change", message: "不能为空" }],
  contacts: [{ required: true, trigger: "change", message: "不能为空" }]
}

onActivated(() => {
  const row = orderInfo().rowData
  getSetOrderInfo(row)
})

//获取数据
const rowData = ref({})
const disabledStus=ref(true)
watch(() => rowData.value, (newVal, oldVal) => { //监听是否可以显示
  if(newVal.status==2){
    if(newVal.frontNodeType >= 10 && newVal.currentNodeType >= 15){
      disabledStus.value=true
    }else{
      disabledStus.value=false
    }
  }else{
    disabledStus.value=true
  }
});
const getSetOrderInfo = async (row: any) => {
  if (!row.id) return
  param.loading = true
  await getOrderInfo(row.id).then((res: any) => {
    const result = res.data
    param.packingInfo = []
    param.packingInfo.push(res.data)
    rowData.value = result
    param.newStep = result.status
    param.checkRadeo=result.currency
    rowData.value.allocation = JSON.parse(result.allocation)
    rowData.value.allocation.forEach((el: any) => {
      el.operateUsers = operateUserFilter(el.operateUser)
    })
    rowData.value.mainFileList = JSON.parse(rowData.value.mainFileList)
    swiperData.list = rowData.value.mainFileList
    param.invoiceUrl = JSON.parse(rowData.value.invoiceUrl)
    param.loading = false
    // param.packingInfo = removeDuplicates(aram.packingInfo,orderNo)
  })
  await getUserSimpleList()
  userSimpleChange(rowData.value.boxEastOperatorUserId)
}

const removeDuplicates = (array:Array,id:any) => {
  Array.from(new Set(array.map(item => item.id))).map(id => {
      return array.find(item => item.id === id);
  });
}


// 获取操作员列表
import { userSimpleList } from '@/api/user/index'
const getUserSimpleList = async (data = {}) => {
  await userSimpleList(data).then(res => {
    param.userSimpleList = res.data || []
  })
}

// 操作员列表change
const userSimpleChange = (val: any) => {
  if (!val) return
  param.userSimpleData = param.userSimpleList.find((item: any) => item.userId == val)
  param.userSimple = val
}

//show 提示窗口 
const handleShowWarning = (val: String) => {
  if (val == 'cancelOrder' || val == 'rejectCancel') { //取消订单、拒绝取消
    param.dialogVisibleWarning = true
    param.warningName = val
  }
  if (val == 'checkReject') { //审核驳回
    handleReject('checkReject')
  }
}
// 取消
const warningForm = ref({ remark: '' })
const handleCancel = () => {
  if (!warningForm.value) {
    return ElMessage({ message: '请输入取消原因', type: 'warning' })
  }
  const data = {
    id: rowData.value.id,
    remark: warningForm.value.remark
  }
  cancelOrder(data).then(res => {
    // param.newStep = 35
    param.dialogVisibleWarning = false
    getSetOrderInfo(rowData.value)
  })
}

//待确认->通过、确认 btn
const handleMakeSure = async () => {
  // if (rowData.value.currentNodeType==10 && param.newStep < 5 && checked1.value==false) return ElMessage({ message: '请阅读并勾选规则协议', type: 'warning' })
  if (!rowData.value.unitPrice) return ElMessage({ message: '租赁单价 不能为空', type: 'warning' })
  if (!rowData.value.boxUsagePeriod) return ElMessage({ message: '箱使期 不能为空', type: 'warning' })
  if (!rowData.value.rate) return ElMessage({ message: '请先确认 执行汇率', type: 'warning' })
  if (!rowData.value || !rowData.value.processId) return ElMessage({ message: 'processId 未找到！', type: 'error' })
  const data = { "processId": rowData.value.processId }
  // const result = await updateBoxPriceAndUsagePeriod()
  const result = await handleUpdateOrder()
  if (result) {
    param.loading = true
    processApproved(data).then(() => {
      ElMessage({ message: '确认成功', type: 'success' })
      getSetOrderInfo(rowData.value)
      param.loading = false
    }).catch((err: any) => {
      param.loading = false
    })
  }
}
//待确认->驳回 btn 
const handleReject = () => {
  if (!rowData.value || !rowData.value.reviewRemark) {
    return ElMessage({ message: '请输入驳回 原因', type: 'warning' })
  }
  if (!rowData.value || !rowData.value.processId) return ElMessage({ message: 'processId 未找到！', type: 'error' })
  const data = { "processId": rowData.value.processId, "reviewRemark": rowData.value.reviewRemark }
  param.loading = true
  processRejected(data).then(() => {
    ElMessage({ message: '驳回成功', type: 'success' })
    getSetOrderInfo(rowData.value)
    param.loading = false
  }).catch((err: any) => {
    param.loading = false
  })
}
//修改订单
import { updateOrderInfo } from '@/api/orderManage/index'
import useUserStore from '@/store/modules/user'
const userStore = useUserStore()
const user = userStore.getUser() //user信息
const handleUpdateOrder = async () => {
  let result = false
  const boxEastOperator = param.userSimpleData
  if (!(boxEastOperator && boxEastOperator.userId)) {
    ElMessage({ message: '请选择操作员', type: 'warning' })
    return false
  }
  if (!validateChengZhi.validateUniPrice(rowData.value.unitPrice)) return false
  if (!validateChengZhi.validateBoxUsagePeriod(rowData.value.boxUsagePeriod)) return false
  const data = {
    "id": rowData.value.id,
    "unitPrice": rowData.value.unitPrice,
    "rate": rowData.value.rate,
    "currency": rowData.value.currency,
    "boxUsagePeriod": rowData.value.boxUsagePeriod,
    "period":rowData.value.period,
    "boxEastOperatorUserId": boxEastOperator.userId,
    "boxEastOperatorUserName": boxEastOperator.nickname,
    "boxEastOperatorUserAreaCode": boxEastOperator.areaCode,
    "boxEastOperatorUserTel": boxEastOperator.mobile,
  }
  await updateOrderInfo(data).then((res: any) => {
    result = true
  })
  return result
}

//开提箱单
const handlePacking = () => {
  // param.packingInfo = {
  //   orderType: rowData.value.orderType, //订单类型 5-租箱 10-回调 15-外调
  //   boxType: rowData.value.boxType,
  //   boxCondition: rowData.value.boxCondition,
  //   planPickupDate: rowData.value.planPickupDate,
  //   createTime: rowData.value.createTime,
  //   priceList: [{ boxType: rowData.value.boxType, boxCondition: rowData.value.boxCondition, number: rowData.value.boxQuantity }], // {boxType:"",boxCondition:"",boxQuantity:"",}
  //   orderNo: rowData.value.orderNo,
  //   id: rowData.value.id, // 订单id
  //   boxQuantity: rowData.value.boxQuantity,
  //   packingAllocationQuantity: rowData.value.packingAllocationQuantity
  // }
  param.drawerPacking = true
}


const successPacking = (id: any) => {
  // param.newStep = 10
  getSetOrderInfo(rowData.value)
  param.drawerPacking = false
  // console.log(id)
}
const closeDialog = () => {
  param.drawerPacking = false
}

// 去开 提箱单/还箱单
const handleCreateOrder = (opt: string) => {
  param.opt = opt
  const data = rowData.value
  if (!validateChengZhi.validateUniPrice(data.unitPrice)) return
  if (!validateChengZhi.validateBoxUsagePeriod(data.boxUsagePeriod)) return
  param.rentOrderTable = [{
    orderNo: data.orderNo,
    planPickupDate: data.planPickupDate,
    createTime: data.createTime,
    id: data.id,
    packingedNum: data.packingAllocationQuantity || 0, // 已开箱量
    unPackingNum: numSub(data.packedQuantity, data.packingAllocationQuantity),// 未开箱量
    returnedNum: data.returnedQuantity || 0,// 已还箱量
    unReturnNum: numSub(data.packedQuantity, data.returnedQuantity)// 未还箱量
  }]
  param.rentBoxTable = [{ boxType: boxTypeFilter(data.boxType), boxQuantity: data.boxQuantity, boxCondition: boxConditionFilter(data.boxCondition) }]
  param.returnBoxType = 10 //默认值
  param.drawer1 = true
  // param.drawerAddPanel = true
  // getSetOrderInfo(rowData.value)
}

//选择租箱订单
let selectList = ref([])
const handleChoice = () => {
  param.drawer = false
  selectList.value.forEach((el: any) => {
    param.rentOrderTable.push({ orderNo: el.orderNo, planPickupDate: el.planPickupDate, createTime: el.createTime, id: el.id })
    param.rentBoxTable.push({ boxType: el.boxType, boxQuantity: el.boxQuantity, boxCondition: el.boxCondition })
  })
}
const handleSelectionChange = (list: any) => {
  selectList.value = list
  console.log(list)
}
//选择集装箱
const choiceBox = () => {
  getBoxInYard()
  param.drawer2 = true
}
let selectBoxList = ref([])
const handleChoiceBox = () => {
  param.drawer2 = false
}
const handleSelectionBoxChange = (list: any) => {
  selectBoxList.value = list
  console.log(list)
}

//开提箱单/开还箱单
const { proxy } = getCurrentInstance();
const handleSubmit = (drawer: string, step: number) => {
  console.log(step)
  if (step == 10) { // 10-开提箱单
    proxy.$refs.packingFormRef.validate(valid => {
      if (!valid) return param.isLoading = false
      handleAddPacking(step, drawer)
    })
  }
  if (step == 20) { // 20-上传发票
    saveUploadUrl(step, drawer)
  }
  if (step == 25) { // 25-开还箱单
    proxy.$refs.packingFormRef.validate(valid => {
      if (!valid) return param.isLoading = false
      handleAddReturn(step, drawer)
      // router.back()
    })
  }
}

//开提箱单
const packingRef = ref()
const handleAddPacking = async (step: any, drawer: string) => {
  let orderList = []
  param.rentOrderTable.forEach((el: any) => {
    orderList.push({ "orderId": el.id, "orderNo": el.orderNo, "planPickupDate": el.planPickupDate, "createTime": el.createTime })
  })
  let containerNoList: any[] = []
  selectBoxList.value.forEach((el: any) => {
    containerNoList.push({ "containerId": el.id, "containerNo": el.containerNo })
  })
  const imgList = await packingRef.value.resultList || []
  // console.log(imgList)
  // return
  const data = {
    // orderType: rowData.value.orderType,
    orderType: 5, //订单类型 5-租箱 10-回调
    "boxType": rowData.value.boxType,
    "boxCondition": rowData.value.boxCondition,
    "orderList": JSON.stringify(orderList), //"[{\"orderId\":1,\"orderNo\":\"2222\"}]", jc0706
    "instruction": param.instruction, //放箱指令号
    // "packingValidityPeriodStart": new Date(param.packingValidityPeriod[0]),
    // "packingValidityPeriodEnd": new Date(param.packingValidityPeriod[1]),
    "boxEastYardId": yardInfo.value.id,
    "containerNoList": JSON.stringify(containerNoList), //"[{\"containerId\":1,\"containerNo\":\"2222\"}]" jc0706
    "remark": param.remark || null,
    "packingFileList": JSON.stringify(imgList),
    yardContactSerialNo: yardInfo.value.yardContactSerialNo
  }
  if (param.packingValidityPeriod && param.packingValidityPeriod.length > 0) {
    data.packingValidityPeriodStart = new Date(param.packingValidityPeriod[0])
    data.packingValidityPeriodEnd = new Date(param.packingValidityPeriod[1])
  }
  addPacking(data).then((res: any) => {
    param.orderId = res.data.id
    param[drawer] = false
    getSetOrderInfo(rowData.value)
    param.newStep = step
  })
}

//提箱单详情
const packingInfo = ref({})
const handleShowPacking = () => {
  rentBoxList(rowData.value.id).then((res: any) => {
    param.pkdialogTable = true
    param.packingList = res.data

  }).catch((err: any) => {
    ElMessage.warning("提箱单列表查询失败，请稍后再试")
  })
}

//提箱单信息
const tixiangdanInfoRef=ref()
const showPacking = async (val) => {
  param.pkdialogTable = false
  if (!val.packingId) {
    return ElMessage({ message: '暂无提箱单id信息', type: 'error' })
  }
  tixiangdanInfoRef.value.openBox(val.packingId)
}
//提箱单信息关闭回调
const txClick=(val)=>{
  packingInfo.value=val
}
//提箱单信息列表回调
const txListClick=(val)=>{
  packingInfo.value=val
  param.drawer4=true
}


//查看还箱单详情
const returnInfo = ref({})
const huanxiangdanInfoRef=ref()

const handleShowReturn = () => {
  huanxiangdanInfoRef.value.openBox(rowData.value.returnBoxId)
  param.oprName = 'huanXiang'
}
//还箱单信息关闭回调
const hxClick=(val)=>{
  returnInfo.value=val
  packingInfo.value=val
  packingInfo.value.drawerName = 'back'
}
//还箱单信息列表回调
const hxListClick=(val)=>{
  returnInfo.value=val
  packingInfo.value=val
  packingInfo.value.drawerName = 'back'
  param.drawer4=true
}
//开还箱单
const handleAddReturn = (step: any, drawer: string) => {
  if (selectBoxList.value.length == 0) {
    return ElMessage({ message: '请选择还箱箱号', type: 'warning' })
  }
  let orderList = []
  param.rentOrderTable.forEach((el: any) => {
    orderList.push({ "orderId": el.id, "orderNo": el.orderNo, "planPickupDate": el.planPickupDate, "createTime": el.createTime })
  })
  let containerNoList: any[] = []
  selectBoxList.value.forEach((el: any) => {
    containerNoList.push({ "containerId": el.id, "containerNo": el.containerNo })
  })
  let containerCountList = [{ "boxType": rowData.value.boxType, boxCondition: rowData.value.boxCondition, boxQuantity: rowData.value.boxQuantity }]
  const imgList = packingRef.value.resultList || []
  if (imgList.length == 0) {
    return ElMessage({ message: '请上传附件', type: 'warning' })
  }
  const data = {
    "returnBoxType": param.returnBoxType,
    "orderList": JSON.stringify(orderList), //"[{\"orderId\":1,\"orderNo\":\"2222\"}]",
    "boxEastYardId": yardInfo.value.id,
    "containerNoList": JSON.stringify(containerNoList), //"[{\"containerId\":1,\"containerNo\":\"2222\"}]",
    "containerCountList": JSON.stringify(containerCountList),  //"[{\"boxType\":5,\"boxCondition\":\"10\",\"boxQuantity\":\"11\"}]",
    detailFileList: JSON.stringify(imgList),
    yardContactSerialNo: yardInfo.value.yardContactSerialNo,
    remark: param.remark || null
  }
  if (param.returnBoxType == 5) { // 5-还箱单 10-箱属  15-还箱令
    data.instruction = param.instructionNum
    data.returnValidityPeriodStart = param.returnValidityPeriod[0]
    data.returnValidityPeriodEnd = param.returnValidityPeriod[1]
  }
  if (param.returnBoxType == 10) {
    data.boxOwnerContent = param.boxOwnerContent
    // data.detailFileList = null
  }
  if (param.returnBoxType == 15) {
    // if (returnValidityPeriod.length == 0) return
    data.returnValidityPeriodStart = param.returnValidityPeriod[0]
    data.returnValidityPeriodEnd = param.returnValidityPeriod[1]
    // data.detailFileList = null
  }
  addReturn(data).then((res: any) => {
    // param.orderId = res.data.id
    param.newStep = step
    param[drawer] = false
    getSetOrderInfo(rowData.value)
  })
}



//集装箱公司上传发票（开发票）
const invoiceRef = ref()
const saveUploadUrl = async (step: any, drawer: string) => { // param.invoiceNo
  const resultList = invoiceRef.value.resultList || []
  if (resultList.length == 0) {
    return ElMessage({ message: '请上传发票', type: 'warning' })
  }
  if (!param.invoiceNo) {
    return ElMessage({ message: '请输入发票号', type: 'warning' })
  }
  let dealAmount =rentFeeTotal.value[0].dealAmount // 应收/付 租箱费总计
  let deductAmount = rentFeeTotal.value[0].deductAmount //实收/付 租箱费总计
  let payContainerNum = rentFeeTotal.value[0].needPayContainerNum//应收/付 租箱量总计
  const data = {
      "id": invoiceInfoDatai.value.id,
      "payCurrency": param.payCurrency,
      "rate": param.rate,
      "invoiceNo": param.invoiceNo,
      "invoiceUrl": JSON.stringify(resultList),
      "dealAmount": dealAmount,
      "deductAmount": deductAmount,
      "payContainerNum": payContainerNum,
      "containerNoDetail": JSON.stringify(rentFeeDetail.value),
  
  }
  rentUploadingInvoice(data).then((res: any) => {
    getSetOrderInfo(rowData.value)
    if (step) {
      param.newStep = step
    }
    param[drawer] = false
    param.invoiceNo = null
  })
}
//开发票点击
const drawer5Tap=()=>{
  param.drawer5 = true
  getDetailAndTotal()

}
const invoiceInfoDatai=ref({}) //发票数据回显
const rentFeeDetail=ref([])
const rentFeeTotal=ref([])

//开发票查询
function getDetailAndTotal() {
  getInvoicesInfo(rowData.value.invoiceId).then((res: any) => {
    invoiceInfoDatai.value=res.data
    if(res.data.containerNoDetail){
      rentFeeDetail.value = JSON.parse(res.data.containerNoDetail)
      rentFeeTotal.value = [{ needPayContainerNum: invoiceInfoDatai.value.payContainerNum, dealAmount:invoiceInfoDatai.value.dealAmount, deductAmount: invoiceInfoDatai.value.deductAmount }]
    }  
  })
}
//重新上传
const handleReuploadInvoice = async () => {
  saveUploadUrl(null, 'drawerReuploadInvoice')
}

//过滤
const boxTypeFilter = (val: any) => {
  let result = ''
  const boxConditionList = [{ value: 5, label: '40HQ' }, { value: 10, label: '40GP' }, { value: 15, label: '20HQ' }, { value: 20, label: '20GP' }]
  boxConditionList.forEach((item: { value: any; label: any; }) => {
    if (item.value == val) {
      result = item.label
    }
  })
  return result
}
const boxConditionFilter = (val: any) => {
  let result = ''
  const boxTypeList = [{ value: 5, label: '全新' }, { value: 10, label: '次新' }, { value: 15, label: '适货' }, { value: 20, label: '混提' }]
  boxTypeList.forEach((item: { value: any; label: any; }) => {
    if (item.value == val) {
      result = item.label
    }
  })
  return result
}
const operateUserFilter = (operateUsers: any) => {
  let result: any = []
  if (operateUsers) {
    operateUsers.forEach((el: any) => {
      result.push(el.operateUserId)
    })
  }
  return result
}

//堆场组件 emit 
const yardInfo = ref({})
const yardInfoData = (id: string, info: any) => {
  // param.location = id
  console.log(info)
  if (info) {
    param.yardName = info.yardName
    yardInfo.value = info
    //获取联系人&&默认第一个
    yardInfo.value.yardContacts = info.yardContacts ? JSON.parse(info.yardContacts) : []
    handleYardContactsChange(yardInfo.value.yardContacts[0])
  }
}

//数据支持
// 获取 订单列表
function getTableData() {
  let data = {
    pageNum: 1,
    pageSize: 200,
    status: 5, //待提箱未收/付
    orderNo: param.orderNo?.trim()
  }
  getTable(data).then((res: any) => {
    let list = res.data.list;
    list.forEach((el: any) => {
      el.boxType = boxTypeFilter(el.boxType)
      el.boxCondition = boxConditionFilter(el.boxCondition)
    });
    param.selectTable = list;
  });
}

//获取 堆存状态 箱子列表
function getBoxInYard() {
  let data = {
    statusList: [5], //5-堆存中、10-提箱中、15-已提、20-未还、25-还箱中 30-已卖
    containerNo: param.containerNo?.trim(),
    boxType: rowData.value.boxType,
    boxCondition: rowData.value.boxCondition,
    orderType:rowData.value.orderType,
    // boxEastYardId: yardInfo.value.id,
    boxEastOperatorUserId: userStore.getUser().id,
    pageNum: 1,
    pageSize: 200,
  };
  
  // if (param.newStep == 5) {
  //   data.boxEastYardId = yardInfo.value.id
  // }
  if (param.opt == 'huanXiang') {
    data.statusList = [20]//5-堆存中、10-提箱中、15-已提、20-未还、25-还箱中 30-已卖
    data.orderId = rowData.value.id
  }
  getBoxTable(data).then(res => {
    let list = res.data.list;
    list.forEach((el: any) => {
      el.boxType = boxTypeFilter(el.boxType)
      el.boxCondition = boxConditionFilter(el.boxCondition)
    });
    param.selectBoxTable = list;
  });
}

const ocrInvoiceNo = (val: any) => {
  const invoice = val.data
  param.invoiceNo = invoice.invoiceNo
}

// 调取 eQuanBao 长链接
const showContract = async (val: any) => {
  let requestData = {
    "orderId": rowData.value.id,
    "companyId": rowData.value.companyId,
    "businessType": 5
  }
  param.loading = true
  getEqbContractOrderInfo(requestData)
  .then((res: any) => {
    param.longContractUrl = res.data.longContractUrl
    if (param.longContractUrl) {
      param.dialogEVisibleWarning = true
    } else {
      getEqbContractOrderInfo(requestData)
      .then((res1: any) => {
        param.longContractUrl = res1.data.longContractUrl
        if(param.longContractUrl){
          param.dialogEVisibleWarning = true
        }else{
          return ElMessage.warning('系统繁忙！请稍后再试')
        }
      }) 
      .catch(() => {
        ElMessage.warning('系统繁忙！请稍后再试')
        param.loading = false
      })
    }
    param.loading = false
  })
  .catch(() => {
    ElMessage.warning('系统繁忙！请稍后再试')
    param.loading = false
  })
}

//联系人切换
const handleYardContactsChange = (val: any) => {
  if (!val) return
  yardInfo.value.contacts = val.contacts
  param.contacts = val.contacts //  to pass jiaoyan
  yardInfo.value.tel = val.tel
  yardInfo.value.areaCode = val.areaCode
  yardInfo.value.email = val.email
  yardInfo.value.yardContactSerialNo = val.yardContactSerialNo
}

// 关闭弹窗
const handleCloseEQianBao = async () => {
  const loading = ElLoading.service({
    lock: true,
    text: '数据更新中...',
    background: 'rgba(0, 0, 0, 0.7)',
  })
  await setTimeout(async () => {
    getSetOrderInfo(rowData.value)
    loading.close()
  }, 10000)
}
// 修改箱使期
const modifyBoxUsagePeriod = ()=>{
  if(rowData.value.frontNodeType >= 10 && rowData.value.currentNodeType >= 15) return ElMessage.warning('当前该节点不能修改相关信息')
  param.modifyType = "boxUsagePeriod"
  param.dialogBoxUsagePeriod = true
  param.boxUsageNumber = ""
}


//修改租赁单价
const modifyUnitPrice = ()=>{
  if(rowData.value.frontNodeType >= 10 && rowData.value.currentNodeType >= 15) return ElMessage.warning('当前该节点不能修改相关信息')
  param.modifyType = "unitPrice"
  param.dialogBoxUsagePeriod = true
  param.unitPriceNumber = ""
}

const confirmNumber = ()=>{
  param.dialogBoxUsagePeriod = false
  if(param.modifyType == "unitPrice"){
    rowData.value.unitPrice =  Number(param.unitPriceNumber).toLocaleString()
  }else if(param.modifyType == "boxUsagePeriod"){
    rowData.value.boxUsagePeriod =  param.boxUsageNumber
  }
}
// 使用正则表达式只允许输入数字
const handleInput = (value: string) => {
  if (param.modifyType === 'unitPrice') {
    param.unitPriceNumber = value.replace(/[^\d.]/g, '').replace(/\.{2,}/g, '.').replace(/(\.\d{2}).+/, '$1'); 
  } else if (param.modifyType === 'boxUsagePeriod') {
    param.boxUsageNumber = value.replace(/[^\d]/g, '');
  }
}

// 选择币种信息
const changeRadio = (val: any) => {
  // console.log("radio",val)
  rowData.value.currency = val
}
// 合计金额
const totalAmount = computed(() => {
  return (
    Number(rowData.value.unitPrice) *
    Number(rowData.value.containerQuantity)
  ).toLocaleString()
})

const changePeriod = (val)=> {
  // console.log(val)
  rowData.value.period = val
}
const newPackingInfo = () => {
  if(param.packingInfo.length > 1){
    return 
  }
}
const packingInfoStr = () => {
  return param.packingInfo
}
provide('packingInfo',packingInfoStr );

provide('config', {
  disable:true, // 订单选择弹窗 筛选项是否可选
  sources: "internal", // 组件引用来源： internal-订单内开提箱单/租箱订单内开提箱单 ， management -提箱管理内开提箱单   
  orderType: 5, // 订单类型 5：租箱 10：回调箱 
  
});

</script>
<style lang="scss" scoped>
.pag-container {
  margin-top: 10px;
  box-sizing: border-box;
  padding: 10px;
}

.order-info {
  margin-top: 10px;
}

table>tr>td~td {
  font-weight: bold;
}
</style>